{% extends "base.html" %}

{% block title %}批量任务 - 安居客租房数据爬取系统{% endblock %}

{% block content %}
<div class="row">
    <div class="col-lg-12">
        <div class="card">
            <div class="card-header bg-success text-white">
                <h4 class="mb-0"><i class="fas fa-layer-group me-2"></i>批量任务管理</h4>
            </div>
            <div class="card-body">
                <div class="row">
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">上传批量配置文件</h5>
                            </div>
                            <div class="card-body">
                                <p class="text-muted">上传JSON格式的批量任务配置文件</p>
                                <form id="uploadForm" enctype="multipart/form-data">
                                    <div class="mb-3">
                                        <label for="configFile" class="form-label">选择配置文件</label>
                                        <input class="form-control" type="file" id="configFile" name="file" accept=".json" required>
                                        <div class="form-text">
                                            配置文件应为JSON格式，包含任务列表。
                                            <a href="javascript:void(0)" onclick="downloadSampleConfig()">下载示例配置</a>
                                        </div>
                                    </div>
                                    <button type="submit" class="btn btn-success" id="uploadBtn">
                                        <i class="fas fa-upload me-2"></i>上传并执行
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-6">
                        <div class="card">
                            <div class="card-header bg-light">
                                <h5 class="mb-0">批量任务说明</h5>
                            </div>
                            <div class="card-body">
                                <h6>配置文件格式：</h6>
                                <pre class="bg-light p-3 small"><code>[
  {
    "city": "广州",
    "district": "天河",
    "min_price": "2000",
    "max_price": "5000",
    "room_type": "二室",
    "max_pages": 3,
    "get_details": false
  },
  {
    "city": "深圳",
    "district": "南山",
    "min_price": "3000",
    "max_price": "8000",
    "room_type": "二室",
    "max_pages": 2,
    "get_details": true
  }
]</code></pre>
                                <div class="alert alert-info">
                                    <small>
                                        <strong>提示：</strong>批量任务会自动间隔执行，避免请求过于频繁。
                                        每个任务完成后会等待10秒再执行下一个任务。
                                    </small>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="card mt-4">
                    <div class="card-header bg-primary text-white">
                        <h5 class="mb-0"><i class="fas fa-list me-2"></i>任务列表</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-3">
                            <button class="btn btn-outline-primary btn-sm" onclick="refreshTaskList()">
                                <i class="fas fa-sync-alt me-1"></i>刷新
                            </button>
                            <span class="text-muted" id="taskSummary">加载中...</span>
                        </div>
                        <div id="taskList" class="table-responsive">
                            <table class="table table-striped table-hover">
                                <thead>
                                    <tr>
                                        <th>任务ID</th>
                                        <th>城市/区域</th>
                                        <th>状态</th>
                                        <th>进度</th>
                                        <th>结果数</th>
                                        <th>开始时间</th>
                                        <th>操作</th>
                                    </tr>
                                </thead>
                                <tbody id="taskListBody">
                                    <tr>
                                        <td colspan="7" class="text-center">加载中...</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<!-- 任务详情模态框 -->
<div class="modal fade" id="taskDetailModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">任务详情</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <div id="taskDetailContent">
                    <p>加载中...</p>
                </div>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 加载任务列表
    refreshTaskList();

    // 设置定时刷新
    setInterval(refreshTaskList, 5000);

    // 文件上传处理
    $('#uploadForm').submit(function(e) {
        e.preventDefault();

        const formData = new FormData();
        const fileInput = $('#configFile')[0];

        if (fileInput.files.length === 0) {
            alert('请选择配置文件');
            return;
        }

        formData.append('file', fileInput.files[0]);

        $('#uploadBtn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin me-2"></i>上传中...');

        $.ajax({
            url: '/upload_batch_config',
            type: 'POST',
            data: formData,
            processData: false,
            contentType: false,
            success: function(response) {
                if (response.success) {
                    alert(response.message);
                    refreshTaskList();
                } else {
                    alert('上传失败: ' + response.message);
                }
                $('#uploadBtn').prop('disabled', false).html('<i class="fas fa-upload me-2"></i>上传并执行');
                $('#configFile').val('');
            },
            error: function() {
                alert('网络错误，请重试');
                $('#uploadBtn').prop('disabled', false).html('<i class="fas fa-upload me-2"></i>上传并执行');
            }
        });
    });
});

// 刷新任务列表
function refreshTaskList() {
    $.get('/get_all_tasks', function(data) {
        const tasks = data.tasks;
        const tbody = $('#taskListBody');

        if (tasks.length === 0) {
            tbody.html('<tr><td colspan="7" class="text-center">暂无任务</td></tr>');
            $('#taskSummary').text('共 0 个任务');
            return;
        }

        // 更新任务摘要
        const completed = tasks.filter(t => t.status === 'completed').length;
        const running = tasks.filter(t => t.status === 'running').length;
        const error = tasks.filter(t => t.status === 'error').length;
        $('#taskSummary').text(`共 ${tasks.length} 个任务 (完成: ${completed}, 运行中: ${running}, 错误: ${error})`);

        // 更新任务列表
        let html = '';
        tasks.forEach(task => {
            const statusBadge = getStatusBadge(task.status);
            const progressBar = getProgressBar(task.progress);
            const startTime = task.start_time ? new Date(task.start_time).toLocaleString() : '-';

            html += `
            <tr>
                <td><small>${task.task_id}</small></td>
                <td>${task.config.city}${task.config.district ? '-' + task.config.district : ''}</td>
                <td>${statusBadge}</td>
                <td>
                    <div class="progress" style="height: 8px;">
                        ${progressBar}
                    </div>
                    <small class="text-muted">${task.progress}%</small>
                </td>
                <td>${task.results_count}</td>
                <td><small>${startTime}</small></td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <button class="btn btn-outline-info" onclick="viewTaskDetail('${task.task_id}')"
                                title="查看详情">
                            <i class="fas fa-info"></i>
                        </button>
                        ${task.status === 'completed' && task.results_count > 0 ?
                          `<button class="btn btn-outline-success" onclick="downloadTask('${task.task_id}')"
                                   title="下载结果">
                                <i class="fas fa-download"></i>
                           </button>` : ''}
                    </div>
                </td>
            </tr>`;
        });

        tbody.html(html);
    }).fail(function() {
        $('#taskListBody').html('<tr><td colspan="7" class="text-center text-danger">加载失败</td></tr>');
    });
}

// 获取状态徽章
function getStatusBadge(status) {
    const statusMap = {
        'pending': { class: 'bg-secondary', text: '等待中' },
        'running': { class: 'bg-primary', text: '执行中' },
        'completed': { class: 'bg-success', text: '已完成' },
        'error': { class: 'bg-danger', text: '错误' }
    };

    const statusInfo = statusMap[status] || { class: 'bg-warning', text: status };
    return `<span class="badge ${statusInfo.class}">${statusInfo.text}</span>`;
}

// 获取进度条
function getProgressBar(progress) {
    const width = Math.min(progress, 100);
    return `<div class="progress-bar" style="width: ${width}%"></div>`;
}

// 查看任务详情
function viewTaskDetail(taskId) {
    $('#taskDetailContent').html('<p>加载中...</p>');
    $('#taskDetailModal').modal('show');

    $.get('/task_status/' + taskId, function(data) {
        if (data.error) {
            $('#taskDetailContent').html(`<p class="text-danger">${data.error}</p>`);
            return;
        }

        let html = `
            <div class="row">
                <div class="col-md-6">
                    <strong>任务ID:</strong> ${data.task_id}<br>
                    <strong>状态:</strong> ${getStatusBadge(data.status)}<br>
                    <strong>进度:</strong> ${data.progress}%<br>
                </div>
                <div class="col-md-6">
                    <strong>开始时间:</strong> ${data.start_time ? new Date(data.start_time).toLocaleString() : '-'}<br>
                    <strong>结束时间:</strong> ${data.end_time ? new Date(data.end_time).toLocaleString() : '-'}<br>
                    <strong>结果数量:</strong> ${data.results_count}<br>
                </div>
            </div>
            <div class="mt-3">
                <strong>消息:</strong><br>
                <div class="alert alert-info">${data.message}</div>
            </div>`;

        if (data.status === 'completed' && data.results_count > 0) {
            html += `
            <div class="mt-3">
                <button class="btn btn-success" onclick="downloadTask('${taskId}')">
                    <i class="fas fa-download me-2"></i>下载结果文件
                </button>
                <button class="btn btn-outline-primary" onclick="viewTaskResults('${taskId}')">
                    <i class="fas fa-eye me-2"></i>查看数据预览
                </button>
            </div>`;
        }

        $('#taskDetailContent').html(html);
    });
}

// 查看任务结果
function viewTaskResults(taskId) {
    $('#taskDetailContent').html('<p>加载中...</p>');

    $.get('/task_results/' + taskId, function(data) {
        if (data.error) {
            $('#taskDetailContent').append(`<p class="text-danger">${data.error}</p>`);
            return;
        }

        let html = `<h6>数据预览 (共 ${data.total_count} 条，显示前 ${data.preview_results.length} 条)</h6>`;

        if (data.preview_results.length > 0) {
            const firstRow = data.preview_results[0];
            html += '<div class="table-responsive" style="max-height: 400px; overflow-y: auto;"><table class="table table-sm table-striped"><thead><tr>';

            // 表头
            for (const key in firstRow) {
                html += `<th>${key}</th>`;
            }
            html += '</tr></thead><tbody>';

            // 数据行
            data.preview_results.forEach(house => {
                html += '<tr>';
                for (const key in firstRow) {
                    let value = house[key] || '';
                    if (typeof value === 'string' && value.length > 50) {
                        value = value.substring(0, 50) + '...';
                    }
                    html += `<td title="${house[key]}">${value}</td>`;
                }
                html += '</tr>';
            });

            html += '</tbody></table></div>';
        } else {
            html += '<p class="text-muted">暂无数据</p>';
        }

        $('#taskDetailContent').html(html);
    });
}

// 下载任务结果
function downloadTask(taskId) {
    window.location.href = '/download/' + taskId;
}

// 下载示例配置
function downloadSampleConfig() {
    const sampleConfig = [
        {
            "city": "广州",
            "district": "天河",
            "min_price": "2000",
            "max_price": "5000",
            "room_type": "二室",
            "max_pages": 3,
            "get_details": false
        },
        {
            "city": "深圳",
            "district": "南山",
            "min_price": "3000",
            "max_price": "8000",
            "room_type": "二室",
            "max_pages": 2,
            "get_details": true
        },
        {
            "city": "北京",
            "district": "朝阳",
            "min_price": "4000",
            "max_price": "10000",
            "room_type": "一室",
            "max_pages": 2,
            "get_details": false
        }
    ];

    const blob = new Blob([JSON.stringify(sampleConfig, null, 2)], { type: 'application/json' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'batch_config_sample.json';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}
</script>
{% endblock %}